package jacker.bit.price;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;

public class PriceHelper extends SQLiteOpenHelper {
	
	public PriceHelper(Context context) {
		// DBNAME sms2mail
		super(context, "pricedb", null, 2); // database version, not app version
		// TODO Auto-generated constructor stub
	}
	
	private static Set<Handler> handlers = new HashSet<Handler>();
	
	public static boolean isUsing(){
		return !handlers.isEmpty();
	}
	
	public static void registerObserver(Handler handler){
		handlers.add(handler);
	}
	
	public static void removeObserver(Handler handler){
		handlers.remove(handler);
	}
	
	public static void notifyUpdate(int flag,boolean delay){
			
			for(Handler handler:handlers){
				android.os.Message mes = new android.os.Message();
				mes.what = flag;
				mes.obj = System.currentTimeMillis();
				handler.removeMessages(flag);
				if(delay)
					handler.sendMessageDelayed(mes,200);
				else
					handler.sendMessage(mes);
			}
			UtilLog.d("handlers count: "+handlers.size());
		
		
	}
	
	public static void hideProgress(){
		for(Handler handler:handlers){
			android.os.Message msg = new android.os.Message();
			msg.what = Consts.MSG_UI_PROGRESS_OFF;
			handler.sendMessage(msg);
		}
    }

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		db.execSQL("create table CURRPRICE (sid INTEGER PRIMARY KEY ASC AUTOINCREMENT,threadid TEXT," +
		"threadname TEXT,price NUM,pricedate INTEGER,origprice NUM,currency TEXT,maxprice NUM,minprice NUM,remind INTEGER default 1)");
		//db.execSQL("create index currprice_threadid on CURRPRICE (threadid)");
		
		db.execSQL("create table PRICES (sid INTEGER PRIMARY KEY ASC AUTOINCREMENT,threadid TEXT," +
				"price NUM,pricedate INTEGER,alarm INTEGER,currency TEXT)");
		db.execSQL("create index prices_thread on PRICES (threadid)");
		
		
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
		if(oldversion<22){
			
			db.execSQL("alter table CURRPRICE add remind INTEGER default 1");
			
		}
	}
	
	public void insertCurrentPrice(CurrentPrice cp){
		SQLiteDatabase db = getWritableDatabase();
		
		ContentValues values = new ContentValues();
		cp.setDate(System.currentTimeMillis());
		setCurrentPriceValues(values,cp);
		db.insert("CURRPRICE", null, values);
		db.close();
		UtilLog.d( "current price added");
		//if(notify)
			notifyUpdate(Consts.MSG_MAIN_DATA_UPDATE,false);
		
	}
	
	
	private void setCurrentPriceValues(ContentValues values,CurrentPrice price){
		values.put("threadid",price.getThreadid() );
		values.put("threadname",price.getThreadname() );
		values.put("price",price.getPrice() );
		values.put("origprice",price.getOrigprice() );
		values.put("pricedate",price.getDate()) ;
		values.put("currency",price.getCurrency()) ;
		values.put("maxprice",price.getMaxprice() );
		values.put("minprice",price.getMinprice() );
		
	}
	
	public void updateCurrentPrice(CurrentPrice cp){
		SQLiteDatabase db = getWritableDatabase();
		ContentValues values = new ContentValues();
		cp.setDate(System.currentTimeMillis());
		setCurrentPriceValues(values,cp);
		db.update("CURRPRICE", values,"threadid=?",new String[]{cp.getThreadid()});
		db.close();
		UtilLog.d( "current price updated");
		//PrefStore.updateTime = System.currentTimeMillis();
		notifyUpdate(Consts.MSG_MAIN_DATA_UPDATE,true);
	}
	
	
	public void insertPrice(Price price){
		SQLiteDatabase db = getWritableDatabase();
		
		ContentValues values = new ContentValues();
		price.setDate(System.currentTimeMillis()) ;
		setPriceValues(values,price);
		long sid = db.insert("PRICES", null, values);
		db.close();
		price.setSid(sid);
		UtilLog.d( "price added");
		//if(notify)
			notifyUpdate(Consts.MSG_DATA_UPDATE,false);
		
	}
	
	
	private void setPriceValues(ContentValues values,Price price){
		values.put("threadid",price.getThreadid() );
		values.put("price",price.getPrice() );
		values.put("alarm",price.getAlarm() );
		values.put("pricedate",price.getDate() );
		values.put("currency",price.getCurrency() );
	}
	
	public void clearPrices(){
		SQLiteDatabase db = getWritableDatabase();
		db.delete("PRICES", null, null);
		db.close();
		
		UtilLog.d( "prices cleared");
		
		notifyUpdate(Consts.MSG_DATA_UPDATE,true);
		
	}
	
	public void deletePrices(String threadid){
		List<Long> sids = new ArrayList<Long>();
		SQLiteDatabase db = getWritableDatabase();
		db.delete("PRICES", "threadid=?", new String[]{threadid});
		db.close();
		
		UtilLog.d( "thread deleted: "+threadid);
		notifyUpdate(Consts.MSG_DATA_UPDATE,true);
	}
	
	public void deletePrice(long sid){
		
		Price email = getPrice(sid);
		
		SQLiteDatabase db = getWritableDatabase();
		db.delete("PRICES", "sid="+sid, null);
		db.close();
		UtilLog.d( "price deleted: "+sid);
		//PrefStore.updateTime = System.currentTimeMillis();
		notifyUpdate(Consts.MSG_DATA_UPDATE,true);
		
		
	}
	
	public void deleteCurrentPrice(String threadid){
		
		SQLiteDatabase db = getWritableDatabase();
		db.delete("CURRPRICE", "threadid=?", new String[]{threadid});
		db.close();
		UtilLog.d( "currprice deleted: "+threadid);
		//PrefStore.updateTime = System.currentTimeMillis();
		notifyUpdate(Consts.MSG_MAIN_DATA_UPDATE,true);
		
		
	}
	

	void setPrice(Cursor cursor,Price mail){
		mail.setSid(cursor.getLong(cursor.getColumnIndex("sid")));
		mail.setDate(cursor.getLong(cursor.getColumnIndex("pricedate")));
		mail.setThreadid(cursor.getString(cursor.getColumnIndex("threadid")));
		mail.setPrice(cursor.getFloat(cursor.getColumnIndex("price")));
		mail.setAlarm(cursor.getInt(cursor.getColumnIndex("alarm")));
		mail.setCurrency(cursor.getString(cursor.getColumnIndex("currency")));
	}
	
	public CurrentPrice getCurrentPrice(String threadid){
		CurrentPrice cp = null;
		SQLiteDatabase db = getReadableDatabase();
		Cursor cursor = db.query("CURRPRICE"
				, null
				, "threadid=?", 
				new String[]{threadid}, null, null, null);
		
		if(cursor.getCount()>0){
			if(cursor.moveToNext()){
				cp = new CurrentPrice();
				setCurrentPrice(cursor,cp);
			}
		}
		cursor.close();
		db.close();
		return cp;
		
	}
	

	void setCurrentPrice(Cursor cursor,CurrentPrice cp){
		cp.setDate(cursor.getLong(cursor.getColumnIndex("pricedate")));
		cp.setThreadid(cursor.getString(cursor.getColumnIndex("threadid")));
		cp.setThreadname(cursor.getString(cursor.getColumnIndex("threadname")));
		cp.setPrice(cursor.getFloat(cursor.getColumnIndex("price")));
		cp.setOrigprice(cursor.getFloat(cursor.getColumnIndex("origprice")));
		cp.setCurrency(cursor.getString(cursor.getColumnIndex("currency")));
		cp.setMaxprice(cursor.getFloat(cursor.getColumnIndex("maxprice")));
		cp.setMinprice(cursor.getFloat(cursor.getColumnIndex("minprice")));
	}
	
	public List<CurrentPrice> getCurrentPrices(){
		List<CurrentPrice> result = new ArrayList<CurrentPrice>();
		SQLiteDatabase db = getReadableDatabase();
		Cursor cursor = db.query("CURRPRICE"
				, null
				, null, 
				null, null, null, null);
		
		if(cursor.getCount()>0){
			while(cursor.moveToNext()){
				CurrentPrice cp = new CurrentPrice();
				setCurrentPrice(cursor,cp);
				result.add(cp);
			}
		}
		cursor.close();
		db.close();
		return result;
		
	}
	
	
	public Price getPrice(long sid){
		Price cp = null;
		SQLiteDatabase db = getReadableDatabase();
		Cursor cursor = db.query("PRICES", null, "sid="+sid, null, null, null, null);
		
		if(cursor.getCount()>0){
			if(cursor.moveToNext()){
				cp = new Price();
				setPrice(cursor,cp);
			}
		}
		cursor.close();
		db.close();
		return cp;
		
	}
	
	
	}
